from luffyapi.libs.yuntongxun.sms import CCP
from rest_framework.response import Response
from rest_framework.views import APIView
from rest_framework import status
from django_redis import get_redis_connection
import random
from rest_framework.generics import CreateAPIView, ListAPIView
from rest_framework.permissions import IsAuthenticated

from .serializers import UserSerializer, UserOrderModelSerializer
from orders.models import Order
from .models import User


# 检验手机号码是否已被注册
class CheckMobileAPIView(APIView):
    def get(self, request, mobile):
        try:
            # 验证成功，说明手机号码已被注册过了
            User.objects.get(mobile=mobile)
            code = status.HTTP_400_BAD_REQUEST
            result = False
        except Exception as e:
            code = status.HTTP_200_OK
            result = True

        return Response({"result": result}, status=code)


# 发送短信接口
class SmsAPiView(APIView):
    def get(self, request, mobile, *args, **kwargs):
        try:
            # 验证成功，说明手机号码已被注册过了
            User.objects.get(mobile=mobile)
            status_code = status.HTTP_400_BAD_REQUEST
            result = False
            message = '手机号码已被注册'
            return Response({"result": result, "message": message})
        except Exception as e:
            pass

        redis = get_redis_connection('sms_code')

        if redis.get('mobile_{}'.format(mobile)):
            return Response({'message': '短信验证码已经发送了，不可以重复请求'})

        captcha = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9']
        # 随机生成4为数字的验证码
        sms_code = ''.join(random.sample(captcha, 4))

        # 设置管道，减少redis连接次数，
        pip = redis.pipeline()
        pip.multi()   # 开启事务
        # 设置验证码每60s发送一次， _ 只是占位符，没啥意义
        pip.setex('mobile_{}'.format(mobile), 60, '_')
        # setex mobile expire sms_code
        # 将手机号码的验证码绑定存储到redis缓存服务器中
        pip.setex('sms_{}'.format(mobile), 300, sms_code)
        pip.execute()  # 执行事务

        ccp = CCP()
        # 注意： 测试的短信模板编号为1[以后申请了企业账号以后可以有更多的模板]
        # 参数1: 客户端手机号码,测试时只能发给测试号码
        # 参数2: 短信模块中的数据
        #        短信验证码
        #        短信验证码有效期提示
        # 参数3: 短信模板的id,开发测试时,只能使用1
        # result返回值  为0表示成功  为-1表示失败
        # result = ccp.send_template_sms(mobile, [sms_code, 5], 1)
        result = 'haha'
        return Response({'result': sms_code, 'message': '发送成功'})


class UserAPIView(CreateAPIView):
    queryset = User.objects.all()
    serializer_class = UserSerializer


class UserOrderAPIView(ListAPIView):
    """用户的订单列表"""
    queryset = Order.objects.all().order_by("-created_time")
    serializer_class = UserOrderModelSerializer
    # permission_classes = [IsAuthenticated]

    def list(self, request, *args, **kwargs):
        # 重写列表查询方法，在数据查询的时候新增当前用户的过滤条件
        queryset = self.filter_queryset(self.get_queryset().filter(user=request.user))

        page = self.paginate_queryset(queryset)
        if page is not None:
            serializer = self.get_serializer(page, many=True)
            return self.get_paginated_response(serializer.data)

        serializer = self.get_serializer(queryset, many=True)

        return Response(serializer.data)
